<template>
<!-- 评论模块 -->
  <div>
    <van-list
    v-model="loading"
    :finished="finished"
    finished-text="没有更多了"
    :immediate-check=false
    @load="onLoad"
    >
      <!-- 具体评论项列表 -->
        <commentItem
        v-for="(item,index) in list" :key="index"
        :comment_item = 'item'
        @reply_click = 'reply_click'
        ></commentItem>
    </van-list>
  </div>
</template>

<script>
import commentItem from './comment-item.vue'
import { getComments } from '@/api/comment'
export default {
  name: 'commentList',
  created () {
    // 手动调用需要手动打开loading
    this.loading = true
    this.onLoad()
  },
  props: {
    source: {
      type: String,
      requried: true
    },
    // type判断是否获取文章列表
    type: {
      type: Boolean,
      // validator:(value)=>{
      //   return
      // }
      default: true
    },
    list: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      // list: [],
      loading: false,
      finished: false,
      offset: '',
      limit: 10
    }
  },
  methods: {
    // 滚动加载
    async onLoad () {
      try {
        // 1.请求数据
        const { data } = await getComments({
          type: this.type ? 'a' : 'c', // type:'a'文章的评论，'b'评论的评论
          source: this.source, // source：文章Id或者评论Id
          offset: this.offset, // offset：获取评论数的偏移量,请求过的数量
          limit: this.limit // limit：每页数量
        })
        // console.log(data)
        // 2.添加到列表中
        const { results } = data.data
        // eslint-disable-next-line vue/no-mutating-props
        this.list.push(...results)
        // 5.拿到评论总数传给父组件
        this.$emit('onload-success', data.data.total_count)
        // 3.关闭加载状态
        this.loading = false
        // 4.判断是否为最后一页
        if (data.data.last_id) {
        // 4.2不是，就更新页码
          this.offset = data.data.last_id
        } else {
        // 4.1是，就结束finished
          this.finished = true
        }
      } catch (err) {
        this.$toast('加载评论失败')
        this.finished = true
        this.loading = true
      }
    },
    reply_click (comment) {
      this.$emit('reply_click', comment)
    }
  },
  components: {
    commentItem
  }
}
</script>

<style>

</style>
